package com.hzy.orderSystem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzy.orderSystem.entities.Support;
import com.hzy.orderSystem.entities.User;
import com.hzy.orderSystem.service.SupportService;
import com.hzy.orderSystem.service.UserService;
import com.hzy.orderSystem.utils.CommonResult;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 小宝
 * @create 2021/4/16 14:22
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserService userService;
    @Autowired
    SupportService supportService;

    /**
     * 登录
     * @param request
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody Map<String, String> request){
        String username = request.get("username");
        String password = request.get("password");
        String role = request.get("role");

        String message = "用户名或者密码错误";
        Object obj = null;

        if(role.equals("user")){
            User user = userService.getUserByUsernameAndPassword(username, password);
            if(user != null && user.getStatus() == 0)
                message = "账号待审核";
            else if(user != null && user.getStatus() == 2)
                message = "账号审核未通过，请重新注册";
            else
                obj = user;
        }
        else
            obj = supportService.getUserByUsernameAndPassword(username, password);

        if(obj != null){
            String token = UUID.randomUUID() + "";
            redisTemplate.opsForValue().set(token, obj, Duration.ofMinutes(30L));

            JSONObject data = new JSONObject();
            data.put("token", token);
            return new CommonResult(20000, "登录成功", data);
        }else
            return new CommonResult(40000, message, null);

    }

    /**
     * 修改密码
     * @param request  request对象，获取token值
     * @param map   newPassword: 新密码 oldPassword: 老密码
     * @return
     */
    @PutMapping("/updatePwd")
    public CommonResult updatePwd(HttpServletRequest request,
                                  @RequestBody Map<String, String> map){
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");
        String token = request.getHeader("X-Token");

        Object obj = redisTemplate.opsForValue().get(token);
        Map<String, String> objMap = JSON.parseObject(
                JSONObject.toJSONString(obj), Map.class
        );
        if(objMap.get("password").equals(oldPassword)){
            String role = objMap.get("role");
            int update = -1;
            // 用户修改
            if(role.equals("user")){
                User user = (User) obj;
                user.setPassword(newPassword);
                obj = user;
                update = userService.updateUser(user);
            }
            // 客服修改
            else{
                Support support = (Support) obj;
                support.setPassword(newPassword);
                obj = support;
                update = supportService.updateSupport(support);
            }
            if(update > 0){
                redisTemplate.opsForValue().set(token, obj, Duration.ofMinutes(30L));
                return new CommonResult(20000, "修改密码成功");
            }else
                return new CommonResult(40000, "系统原因，修改密码失败");
        }else
            return new CommonResult(40000, "原密码错误，请重新输入");
    }

    /**
     * 用户注册
     * @param user  用户名密码等
     * @return
     */
    @PostMapping("/info")
    public CommonResult register(@RequestBody User user){
        // 验证用户名是否已存在
        User userByUsername = userService.getUserByUsername(user.getUsername());
        if(userByUsername == null){
            int save = userService.save(user);
            if(save > 0){
                JSONObject data = new JSONObject();
                data.put("username", user.getUsername());
                return new CommonResult(20000, "用户注册成功", data);
            }
            else
                return new CommonResult(40000, "用户注册失败");
        }else
            return new CommonResult(40000, "用户名已存在");
    }

    /**
     * 获取用户信息
     * @param request  request对象，获取token值
     * @return
     */
    @GetMapping("/info")
    public CommonResult getInfo(HttpServletRequest request){
        // 从请求头中获取token值
        String token = request.getHeader("X-Token");
        Object obj = redisTemplate.opsForValue().get(token);
        // 可以对数据接口进行优化，减少数据交互
        if(obj != null){
            return new CommonResult(20000, "获取用户信息成功", obj);
        }
        else
            return new CommonResult(40000, "登录已失效，请重新登录", null);
    }

    /**
     * 用户注销
     * @param request  request对象，获取token值
     * @return
     */
    @DeleteMapping("/logout")
    public CommonResult logout(HttpServletRequest request){
        // 从请求头中获取token值
        String token = request.getHeader("X-Token");
        Boolean delete = true;
        if(redisTemplate.opsForValue().get(token) != null)
            delete = redisTemplate.delete(token);
        if(delete)
            return new CommonResult(20000, "用户已注销", null);
        else
            return new CommonResult(40000, "用户注销失败", null);
    }

    /**
     * 修改用户或者客服信息、用户审核
     * @param map   修改的字段
     * @param request request对象，获取token值
     * @return
     */
    @PutMapping("/info")
    public CommonResult updateInfo(@RequestBody Map<String, String> map,
                                   HttpServletRequest request) {
        String token = request.getHeader("X-Token");
        String role = map.get("role");

        Object obj = redisTemplate.opsForValue().get(token);
        Map<String, String> objMap = JSON.parseObject(
                JSONObject.toJSONString(obj), Map.class
        );
        int update = -1;
        // 修改用户信息
        if (role.equals("user")) {
            User user = JSONObject.parseObject(JSONObject.toJSONString(map), User.class);
            update = userService.updateUser(user);
            obj = user;
        }
        // 修改客服信息
        else {
            Support support = JSONObject.parseObject(JSONObject.toJSONString(map), Support.class);
            update = supportService.updateSupport(support);
            obj = support;
        }
        if (update > 0){
            if(objMap.get("role").equals(role)){
                redisTemplate.opsForValue().set(token, obj, Duration.ofMinutes(30L));
            }
            return new CommonResult(20000, "修改成功", map);
        }
        else
            return new CommonResult(40000, "系统原因，修改失败");
    }

    /**
     * 获取用户分页列表
     * @param map  status: 用户审核状态
     *             pageSize: 页大小
     *             pageNum: 第几页
     * @return
     */
    @PostMapping("/users")
    public CommonResult getUsers(@RequestBody Map<String, String> map){
        int status = Integer.parseInt(map.get("status"));
        int pageSize = Integer.parseInt(map.get("pageSize"));
        int pageNum = Integer.parseInt(map.get("pageNum"));

        PageHelper.startPage(pageNum, pageSize);
        Page<User> users = userService.getUsersByStatus(status);

        if(users != null){
            JSONObject data = new JSONObject();
            data.put("users", users);
            data.put("total", users.getTotal());
            return new CommonResult(20000, "获取用户列表成功", data);
        }else
            return new CommonResult(40000, "系统原因，获取用户列表失败");
    }
}
